import Vue from 'vue'
import VueRouter from 'vue-router'
import {getUserByToken} from '../request/api'
import store from '../store'
// import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component:()=>import(/* webpackChunkName: "login" */ '../views/login/Login.vue')
  },

  // {
  //   path: '/home',
  //   name: 'Home',
  //   component:()=>import(/* webpackChunkName: "login" */ '../views/homepage/Home.vue'),
  //   children:[
     
  //   ]
  // },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]
const dynamicRoutes={
  '/good':{
    path: '/good',
    name: 'Good',
    component:()=>import(/* webpackChunkName: "good" */ '../views/good/Good.vue')
  },
  '/category':{
    path: '/category',
    name: 'Category',
    component:()=>import(/* webpackChunkName: "category" */ '../views/category/Category.vue')
  },
  '/attribute':{
    path: '/attribute',
    name: 'Attribute',
    component:()=>import(/* webpackChunkName: "attribute" */ '../views/attribute/Attribute.vue')
  }
}
const router = new VueRouter({
  routes
})
router.beforeEach((to,from,next)=>{
  console.log(to,from);
  let token=localStorage.getItem('token')
  // if(to.path!='/login'&&token&& !(to.path=='/home'&&from.path=='/login')){
  if(to.path!='/login'&&token&& store.state.menu.length==0){
    // 发送请求
    getUserByToken().then(res=>{
      console.log(res);
      if(res.errno===0){
        store.commit("SaveMenu",res.data.menu)
        // 动态添加路由配置
        let newRotes=[];
        for(let i=0;i<res.data.menu.length;i++){
          let path =res.data.menu[i].path
          if(dynamicRoutes){
            newRotes.push(dynamicRoutes[path])
          }
        }
        console.log(newRotes);
        // 添加路由配置
        router.addRoute([
          {
            path: '/home',
            name: 'Home',
            component:()=>import(/* webpackChunkName: "login" */ '../views/homepage/Home.vue')
          }
        ])
        next()
      }else{
        // 失败
        localStorage.clear()
        next('/login')
      }
    })
  }else if(!token && to.path!='/login'){
    next('/login')
  }else{
    next()
  }
})

export default router
